# views.py
from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.response import Response

from .entryserializers import CandidateSerializer, CandidateDetailSerializer, InterviewAssignSerializer
from .models import Candidate

class EntryViewSet(viewsets.ModelViewSet):
    queryset = Candidate.objects.all()

    # 1. 动态选择序列化器：列表用精简的，详情用完整的
    def get_serializer_class(self):
        if self.action == 'list':  # 展示列表
            return CandidateSerializer
        elif self.action == 'retrieve':  # 展示候选人详情
            return CandidateDetailSerializer

        return CandidateDetailSerializer

    # 2. 可选：添加过滤和排序（方便按条件展示）
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    # 可按哪些字段过滤（如按部门、职位筛选）
    filterset_fields = ['apply_department', 'apply_position', 'first_interview_result']
    # 可按哪些字段排序（如按创建时间、年龄）
    ordering_fields = ['create_time', 'age']
    # 默认排序（按创建时间倒序，最新的在前面）
    ordering = ['-create_time']

    @action(detail=True, methods=['post'])
    def assign_interview(self, request, pk=None):
        candidate = self.get_object()    # 获取求职者
        serializer = InterviewAssignSerializer  # 序列化数据

        if serializer.vaildate():
            round = serializer.validated_data['round']
            interview_id = serializer.validated_data["interview_id"]
            interview_date = serializer.validated_data['interview_date']

            result_field = f"{round}_interview_result"
            if getattr(candidate,result_field) != 0:
                return Response(
                    {'error':f"{round}面当前不是待处理状态无法安排面试官"},
                    status = 400
                )
            from staff.models import Employee
            interview = Employee.objects.get(id = interview_id)
            setattr(candidate,f"{round}_interviewer",interview)
            setattr(candidate,f"{round}_interview_date",interview_date)
            candidate.save()

            detail_serializer = CandidateDetailSerializer(candidate)
            return  Response(detail_serializer.data)
        return Response(serializer.errors, status = 400)

